"""
修复字段问题的迁移脚本
"""
from sqlalchemy import create_engine, text
from config import settings

def fix_field_issues():
    """修复字段问题"""
    # 创建数据库引擎
    engine = create_engine(settings.database_url)
    
    with engine.begin() as conn:
        try:
            # 1. 为email_configs表的use_ssl字段添加默认值
            print("正在为email_configs表的use_ssl字段添加默认值...")
            conn.execute(text("ALTER TABLE email_configs MODIFY COLUMN use_ssl TINYINT(1) NOT NULL DEFAULT 0"))
            print("✅ use_ssl字段默认值设置成功")
            
            # 2. 为email_configs表的use_starttls字段添加默认值并重命名为use_tls
            print("正在为email_configs表的use_starttls字段添加默认值...")
            conn.execute(text("ALTER TABLE email_configs MODIFY COLUMN use_starttls TINYINT(1) NOT NULL DEFAULT 0"))
            print("✅ use_starttls字段默认值设置成功")
            
            print("正在将use_starttls字段重命名为use_tls...")
            conn.execute(text("ALTER TABLE email_configs CHANGE COLUMN use_starttls use_tls TINYINT(1) NOT NULL DEFAULT 0"))
            print("✅ 字段重命名成功")
            
            # 3. 为data_sources表添加description字段
            print("正在为data_sources表添加description字段...")
            conn.execute(text("ALTER TABLE data_sources ADD COLUMN description TEXT NULL COMMENT '数据源描述'"))
            print("✅ description字段添加成功")
            
            print("✅ 所有字段问题修复完成")
            
        except Exception as e:
            print(f"修复字段失败: {e}")
            # 检查字段是否已存在或已修复
            try:
                # 检查data_sources表的description字段
                result = conn.execute(text("SHOW COLUMNS FROM data_sources LIKE 'description'"))
                if result.fetchone():
                    print("ℹ️ data_sources.description字段已存在")
                else:
                    print("❌ data_sources.description字段不存在，需要手动添加")
                    
            except Exception as check_error:
                print(f"检查字段失败: {check_error}")

if __name__ == "__main__":
    fix_field_issues()
